<?php
namespace hema\delivery;

use hema\delivery\engine\Uu;
use hema\delivery\engine\Dada;
use hema\delivery\engine\Sf;
use hema\delivery\engine\Make;

/**
 * 第三方配送模块驱动
 */
class Driver
{
    private $engine;    // 当前引擎类
    private $delivery = [
        'uu' => 'UU跑腿',
        'dada' => '达达快送',
        'sf' => '顺丰同城',
        'make' => '码科配送'
    ];
    /**
     * 云设备引擎类列表
     */
    const ENGINE_CLASS_LIST = [
        'uu' => Uu::class,
        'dada' => Dada::class,
        'sf' => Sf::class,
        'make' => Make::class
    ];

    /**
     * 构造方法
     */
    public function __construct($company = '')
    {
        if(!empty($company)){
            // 实例化当前引擎
            if(!$config = get_addons_config($company)){
                die(json_encode(['code' => 0, 'msg' => '未安装《' . $this->delivery[$company] .'》插件']));
            }
            $class = self::ENGINE_CLASS_LIST[$company];
            $this->engine = new $class($config);
        }
    }
    
    /**
     * 预发布订单
     */
    public function preOrder($data)
    {
        return $this->engine->preOrder($data);
    }

    /**
     * 添加订单
     */
    public function addOrder($data)
    {
        return $this->engine->addOrder($data);
    }
    /**
     * 取消订单
     */
    public function cancelOrder($order_no)
    {
        return $this->engine->cancelOrder($order_no);
    }
    /**
     * 取消订单
     */
    public function getCiytCode($city)
    {
        return $this->engine->getCiytCode($city);
    }
    
    /**
     * 获取支持的配送公司
     */
    public function company()
    {
        $company = [];
        foreach ($this->delivery as $key=>$item) {
            if($dv = get_addons_info($key)){
                if($dv['status'] == 1){
                    $dv['config'] = get_addons_config($key);
                    $company[] = $dv;
                }
            }
        }
        return $company;
    }
    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->engine->getError();
    }

}
